import {createSlice} from '@reduxjs/toolkit'

export const todoSlicer = createSlice({
  name: 'todo',
  initialState: {
    todos: [
      {id: 1, name: '床前明月光', done: false},
      {id: 2, name: '疑是地上霜', done: false},
      {id: 3, name: '举头望明月', done: false},
      {id: 4, name: '低头思故乡', done: false}
    ]
  },
  reducers: {
    addTodo(state, payload) {
      state.todos = [payload.payload, ...state.todos]
    },
    deleteTodo(state, payload) {
      state.todos = state.todos.filter(todo => {
        return todo.id !== payload.payload
      })
    },
    changeTodo(state, payload) {
      state.todos = state.todos.map(todo => {
        if (todo.id === payload.payload.id) {
          todo.done = payload.payload.done
          return todo
        } else {
          return todo
        }
      })
    },
    checkAllTodos(state, payload) {
      state.todos = state.todos.map(todo => {
        todo.done = payload.payload
        return todo
      })
    },
    clearDoneTodos(state) {
      state.todos = state.todos.filter(todo => {
        return !todo.done
      })
    }
  }
})

export const {addTodo, deleteTodo, changeTodo, checkAllTodos, clearDoneTodos} = todoSlicer.actions
export default todoSlicer.reducer
